package cn.txm.product.Controller;

import cn.txm.basic.util.AjaxResult;
import cn.txm.basic.util.RedisUtils;
import cn.txm.product.domain.Shopcart;
import cn.txm.product.service.IShopcartService;
import cn.txm.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
public class ShopcartController {
    @Autowired
    private IShopcartService shopcartService;

    /**
     * 加入购物车
     * @param shopcart
     * @return
     */
    @PutMapping("/shopcart")
    public AjaxResult addShopcart(@RequestBody Shopcart shopcart, HttpServletRequest request){
        try {
            //获取当前登录用户
            User user = RedisUtils.INSTANCE.getUser(request, User.class);
            shopcart.setUser_id(user.getId());
            shopcartService.add(shopcart);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("购物车加入失败，正在殴打程序员"+e.getMessage());
        }
    }
    /**
     * 根据当前登录用户id，查询它的购物车数据
     * @param request
     * @return
     */
    @GetMapping("/shopcart")
    public List<Shopcart> getMyShopcarts(HttpServletRequest request){
        //获取当前登录用户
        User user = RedisUtils.INSTANCE.getUser(request, User.class);
        //根据当前登录用户id,查询它的购物车数据
        return shopcartService.getMyShopcarts(user.getId());
    }

}
